/**
 * Place holder for copyright, needs to be replaced before release.
 */
package com.softao.ming.gwt.internal.ui.client.workbench;

import com.google.gwt.user.client.ui.RootPanel;
import com.softao.ming.gwt.core.runtime.client.application.IConfigurationElement;
import com.softao.ming.gwt.core.runtime.client.application.IExtension;
import com.softao.ming.gwt.core.runtime.client.application.IExtensionPoint;
import com.softao.ming.gwt.core.runtime.client.application.IExtensionRegistry;
import com.softao.ming.gwt.core.runtime.client.application.Platform;
import com.softao.ming.gwt.ui.client.IPageLayout;
import com.softao.ming.gwt.ui.client.IPerspectiveFactory;
import com.softao.ming.gwt.ui.client.IWorkbench;
import com.softao.ming.gwt.ui.client.IWorkbenchAdvisor;

/**
 * Root class for managing the all page related stuff.
 */
public class Workbench implements IWorkbench {
	private final IWorkbenchAdvisor mAdvisor;

	/**
	 * @param advisor 
	 */
	public Workbench(IWorkbenchAdvisor advisor) {
		mAdvisor = advisor;
	}
	
	/**
	 */
	public void createAndRunWorkbench() {
		String perspectiveId = mAdvisor.getInitialWindowPerspectiveId();
		IPerspectiveFactory perspective = getPerspective(perspectiveId);
		if (perspective == null) {
			throw new RuntimeException("perspective can not be found:" + perspectiveId);
		}
		
		IPageLayout layout = perspective.createPageLayout();
		perspective.createInitialLayout(layout);
		RootPanel.get().clear();
		RootPanel.get().add(layout.getLayoutWidget());
	}
	
	private IPerspectiveFactory getPerspective(String perspectiveId) {
		IExtensionRegistry registry = Platform.getExtensionRegistry();
		IExtensionPoint extensionPoint = registry.getExtensionPoint("com.softao.ming.gwt.ui.perspectives");
		for (IExtension extension : extensionPoint.getExtensions()) {
			for (IConfigurationElement element : extension.getConfigurationElements()) {
				if (element.getName().equals("perspective")) {
					if (perspectiveId.equals(element.getAttribute("id"))) {
						String className = element.getAttribute("class");
						return Platform.getObjectFactory().create(IPerspectiveFactory.class, className);
					}
				}
			}
		}
		
		return null;
	}
}
